#!/usr/bin/python

from alignment import *
from sequence import Sequence
import sys

def expand(node):
    "This function is used to iterate over all the possible sequences of max_len."
    global max_dist
    global max_len
    global consensus
    global predict

    # if this node is of length desired, no need to extend further. check for false positive
    #print len(node)
    s = Sequence(node)
    if len(node) == max_len:
        #s = Sequence(node)
        # distance of sequence from consensus
        d = s.distance(consensus)
        # s is nearer or at same distance as alignment at maximum distance from consensus
        if d <= max_dist:
            # check if it is in real alignments as all real alignments also satisfy above conditions
            predict.append(node)
    elif not (consensus.minDistance(s) > max_dist):
        expand(node+'a')
        expand(node+'c')
        expand(node+'g')
        expand(node+'t')

a = [1, -1, 1]
c = [-1, -1, -1]
g = [-1, 1, 1]
t = [1, 1, -1]

file = Alignment(sys.argv[1])
#print file
print file.Best, file.sequences[file.Best]
print file.Worst, file.sequences[file.Worst]
mat = file.freq_matrix()
file.print_freq_matrix()
print

con = []

for pos in xrange(file.Length):
    tri = [0, 0, 0]
    freq = mat[pos]
    base_freq = [freq*i for i in a]
    
    for j in xrange(len(tri)):
        tri[j] += base_freq[j]
        
    freq = mat[pos+file.Length*1]
    base_freq = [freq*i for i in c]

    for j in xrange(len(tri)):
        tri[j] += base_freq[j]
        
    freq = mat[pos+file.Length*2]
    base_freq = [freq*i for i in g]

    for j in xrange(len(tri)):
        tri[j] += base_freq[j]

    freq = mat[pos+file.Length*3]
    base_freq = [freq*i for i in t]

    for j in xrange(len(tri)):
        tri[j] += base_freq[j]
        
    for k in tri:
        con.append((int)(round(k)))
        
consensus = Sequence(file.sequences[0])
for i in xrange(len(consensus.data)):
    consensus.data[i] = con[i]

for seq in file.sequences:
    s1 = Sequence(seq)
    print s1.distance(consensus)

bases = ['a', 'c', 'g', 't']
s2 = Sequence(file.sequences[file.Worst])
max_dist = s2.distance(consensus)

max_len = file.Length
print "max", max_len
predict = []
for b in bases:
    expand(b)
print file.Best
    
print "................."
for p in predict:
    print p
    
print len(predict)